#include <QApplication>
#include <QQmlApplicationEngine>
#include "singleapplication.h"
#include <QQmlContext>
#include <QtQml>
#include <QFont>
#include "httphelper.h"
#include "commonhelper.h"
#include "userhelper.h"
#include "scannerhelper.h"

#define USER_SINGLE
QString targetFilePath;
void initDebugOutput()
{
    static auto defaultHandler = qInstallMessageHandler( nullptr );

    targetFilePath = QString( "%1/logs/%2_%3.txt" ).arg(  QStandardPaths::writableLocation( QStandardPaths::AppConfigLocation ), qApp->applicationName(), QDateTime::currentDateTime().toString( "yyyyMMdd" ) );

    class HelperClass
    {
    public:
        static void messageHandler(QtMsgType type, const QMessageLogContext &context, const QString &rawMessage)
        {
            QString message;
            if ( !QFileInfo::exists( targetFilePath ) )
            {
                QDir().mkpath( QFileInfo( targetFilePath ).path() );
            }

            switch ( type )
            {
            case QtDebugMsg:
            {
                message = rawMessage;
                break;
            }
            case QtWarningMsg:
            {
                message.append( "Warning: " );
                message.append( rawMessage );
                break;
            }
            case QtCriticalMsg:
            {
                message.append( "Critical: " );
                message.append( rawMessage );
                break;
            }
            case QtFatalMsg:
            {
                message.append( "Fatal: " );
                message.append( rawMessage );
                break;
            }
            case QtInfoMsg:
            {
                message.append( "Info: " );
                message.append( rawMessage );
                //                QFile file( targetFilePath );

                //                file.open( QIODevice::WriteOnly | QIODevice::Append );
                //                file.write( QString( "%1: %2\n" ).arg( QDateTime::currentDateTime().toString( "yyyy-MM-dd hh:mm:ss" ), message).toUtf8() );
                break;
            }
            default: { break; }
            }



            ( *defaultHandler )( type, context, rawMessage );

            QFile file( targetFilePath );
            file.open( QIODevice::WriteOnly | QIODevice::Append );
            file.write( QString( "%1: %2\n" ).arg( QDateTime::currentDateTime().toString( "yyyy-MM-dd hh:mm:ss" ), message).toUtf8() );
        }
    };

    qInstallMessageHandler( HelperClass::messageHandler );
}


int main(int argc, char *argv[])
{
    qSetMessagePattern( "%{time hh:mm:ss.zzz}: %{message}" );
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
    QCoreApplication::setOrganizationName( "xuantianhu" );
    QCoreApplication::setApplicationName( "xthleyuan" );

    //    QApplication     app( argc, argv );
    SingleApplication app(argc, argv,"xthleyuan");
#ifdef USER_SINGLE
    if (app.isRunning())
    {
        app.sendMessage("raise_window_noop");
        return 0;
    }
#endif
    initDebugOutput();
    QObject::connect(&app, &SingleApplication::messageAvailable, &app, &SingleApplication::activeRunWindow);
    QFont f("微软雅黑");
    f.setPixelSize(14);
    app.setFont(f);
    QQmlApplicationEngine engine;
    WTHTTP_QML_INIT( &engine );
    engine.rootContext()->setContextProperty( "ScannerHelper", ScannerHelper::instance() );
    engine.rootContext()->setContextProperty( "CommonHelper", CommonHelper::instance() );
    engine.rootContext()->setContextProperty( "UserHelper", UserHelper::instance() );
    engine.rootContext()->setContextProperty( "HttpHelper", HttpHelper::instance() );
    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
        &app, [url](QObject *obj, const QUrl &objUrl) {
            if (!obj && url == objUrl)
                QCoreApplication::exit(-1);
        }, Qt::QueuedConnection);
    engine.load(url);
#ifdef USER_SINGLE
    if(engine.rootObjects().size() > 0)
    {
        QWindow * win= qobject_cast<QWindow*>(engine.rootObjects().first());
        app.set_run_widget(win);
    }
#endif
    qDebug() << "QSslSocket version:" << QSslSocket::sslLibraryBuildVersionNumber()<<QSslSocket::supportsSsl()<<QSslSocket::sslLibraryVersionString();
    return app.exec();
}
